<template>
  <div class="wrapper">
    <JTable ref="JTable" :table-list="dataList" :config="tableConfig">
      <template slot="Actions" slot-scope="{row}">
        <el-button type="text" @click="handleActive(row,'more')">详情</el-button>
        <el-button v-if="$_permisson('/core/tenant/update')" type="text" @click="handleActive(row,'edit')">修改</el-button>
        <el-button v-if="$_permisson('/core/tenant/delete')" type="text" @click="handleActive(row,'del')">删除</el-button>
      </template>
      <template slot="activeBoxR">
        <el-button v-if="$_permisson('/core/tenant/setting')" @click="showCreate('quota')">授权配置</el-button>
      </template>
      <template slot="accountNumber" slot-scope="scope">
        <el-tag v-if="scope.row.accountNumber === -1">不限制</el-tag>
        <el-tag v-else>{{ scope.row.accountNumber }}</el-tag>
      </template>

      <template slot="expireTime" slot-scope="scope">
        <el-tag v-if="scope.row.expireTime">{{ scope.row.expireTime }}</el-tag>
        <el-tag v-else>不限制</el-tag>
      </template>
    </JTable>

    <el-dialog
      :title="dialog.title[dialog.active]"
      :width="dialog.active==='quota'?'30%':'60%'"
      :visible.sync="dialog.dialogVisible"
      destroy-on-close
    >
      <createdWidget
        v-if="['created','edit','more'].includes(dialog.active)"
        :emit-data="emitData"
        :read="dialog.active=='more'"
        @handleBoxEvent="handleDialog"
      />
      <quotaWidget
        v-if="dialog.active==='quota'"
        :emit-data="emitDataQuota"
        @handleBoxEvent="handleQuota"
      />
    </el-dialog>
  </div>
</template>

<script>
import createdWidget from './widget/created'
import quotaWidget from './widget/quota'
import pageBtn from '@/views/mixin/pageBtn'
import JTable from '@/components/JTable'

import { list, add, removeItem, updateItem, useSetting } from '@/api/tenant'
export default {
  components: {
    createdWidget,
    quotaWidget,
    JTable
  },
  mixins: [pageBtn],
  props: {},
  data() {
    const listQuery = {
      total: 0,
      page: 1,
      size: 10,
      handleFilter: this.fetchData
    }
    const dialog = {
      dialogVisible: false,
      title: { created: '创建租户', edit: '修改租户', quota: '额度配置' },
      active: ''
    }
    return {
      listQuery,
      dialog,
      listLoading: false,
      dataList: [],
      tableConfig: {
        listLoading: this.listLoading,
        pagination: listQuery,
        thead: [
          {
            type: 'selection'
          },
          {
            type: 'index',
            label: '-',
            start: 1,
            width: 50
          },
          {
            prop: 'tenantName',
            label: '租户名称'
          },
          {
            prop: 'tenantCode',
            label: '租户Code'
          },
          {
            prop: 'accountNumber',
            label: '账号额度',
            slot: true
          },
          {
            prop: 'address',
            label: '联系地址'
          },
          {
            prop: 'backgroundUrl',
            label: '系统背景'
          },
          {
            prop: 'contactName',
            label: '联系人'
          },
          {
            prop: 'contactPhone',
            label: '联系电话'
          },
          {
            prop: 'domain',
            label: '域名地址'
          },
          {
            prop: 'expireTime',
            label: '过期时间',
            slot: true
          },
          {
            prop: '',
            label: 'Actions',
            type: 'actions',
            width: '150',
            align: 'center',
            slot: true
          }
        ],
        search: {
          // labelWidth: '80px',
          searchList: [
            'tenantName',
            'tenantCode',
            'contactName'
          ]
        },
        activeBox: {
          defaultBtn: ['created'],
          btnRules: { created: '/core/tenant/add', rulesFuntion: this.$_permisson }, // 按btn个数重左向右
          bindDefaultEvent: this.showCreate
        },
        tableEvent: {
          'selection-change': this.selectionChange
        }
      },
      currentId: '',
      currentActive: []
    }
  },
  computed: {
    emitData() {
      const { currentId } = this
      if (currentId === null) return {}
      const result = this.dataList.find(i => i.id === currentId)
      return result || {}
    },
    emitDataQuota() {
      const selection = this.$refs.JTable.selection
      if (selection.length) {
        return selection
      }
      return []
    }
  },
  watch: {},
  created() {
    this.fetchData()
  },
  mounted() {},
  methods: {
    selectionChange(selection) {
      this.currentActive = selection
    },
    fetchData(argm = {}) {
      this.listLoading = true
      const { page: pageNum = 1, size: pageSize = 10, ...param } = argm
      const params = { pageNum, pageSize, ...param }

      list(params).then(res => {
        const { /* code, */ data: { records: list = [], total = 0 }} = res
        this.dataList = list
        this.listQuery.total = total
        this.listLoading = false
      })
    },
    showCreate(target = 'created') {
      if (target === 'quota') {
        if (!this.emitDataQuota.length) {
          return this.$message('请选择要操作的数据')
        }
      }
      // 'created' 'showCreate'
      this.showDialog(target)
    },
    showDialog(target) {
      this.dialog.dialogVisible = true
      this.dialog.active = target
    },
    hiddenDialog() {
      this.dialog.dialogVisible = false
      this.currentId = null
    },
    handleQuota({ target = {}}) {
      const activeId = this.currentActive.reduce((p, c, i) => {
        const { id } = c
        if (p) {
          p += ','
        }
        p += id
        return p
      }, '')
      useSetting({ ids: activeId, ...target }).then((res) => {
        const { code } = res
        if (code === 200) {
          this.$message.success('设置成功')
          this.hiddenDialog()
        }
      })
    },
    handleDialog(emit) {
      const { target } = emit
      if (!target) {
        return this.hiddenDialog()
      }
      const currentActive = this.dialog.active
      if (currentActive === 'created') {
        this.createdItem(target)
      }
      if (currentActive === 'edit') {
        this.updateItem(target)
      }
      this.hiddenDialog()
    },

    updateItem(newData) {
      const params = { ...newData, id: this.currentId }
      updateItem(params).then(res => {
        const { code, message } = res
        if (code === 200) {
          this.$message({
            message,
            type: 'success'
          })
          this.fetchData()
          return
        }
        this.$message.error(message)
      })
    },

    createdItem(item) {
      add(item).then(res => {
        this.fetchData()
      })
    },

    handleFilter() {},
    handleActive(row, target) {
      const { id } = row
      this.currentId = id
      if (target === 'del') {
        this.bindRemoveItem()
        return
      }

      if (target === 'effect') {
        const { code } = row
        this.bindTakeEffect(code)
        return
      }

      if (['more', 'edit'].includes(target)) {
        const openTarget = target
        this.showDialog(openTarget)
      }
    },

    /**
     * @description: 删除一个参数
     * @param {*}
     * @return {*}
     */
    bindRemoveItem() {
      this.$confirm('确认删除').then(res => {
        const id = this.currentId
        removeItem(id).then(res => {
          const { code, message } = res
          if (code === 200) {
            this.$message({
              message,
              type: 'success'
            })
            this.fetchData()
            return
          }
          this.$message.error(message)
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.wrapper{
   padding: 0px;
   margin: 0px;
}
</style>
